package EMAIL_VISION::Tracker::API::UriGenerator;

use base qw (Exporter);
use strict;
use DE_EPAGES::Core::API::Log qw (LogDebug GetLog);
use URI::Escape;
use DateTime;
use Data::Dumper;


sub new {
	my ($class, $Order) = @_;
	my $self->{Order} = $Order;
	bless $self, $class;
	return $self;
}

sub getUri
{
    my ($self) = @_;
    my $Order = $self->{Order};
    return unless $Order;
    return unless eval { $Order->get('OrderID') };

    my $LineItemContainer = eval { $Order->get('LineItemContainer') };
    return unless $LineItemContainer;

    my $User = eval { $Order->get('User') };
    return unless $User;

    my $BillingAddress = eval { $User->get('BillingAddress') };
    return unless $BillingAddress;

    #Valid Email Vision parameters:
    #emv_client_id:     - mapped to MBO $Shop -> 'EVCustomerNumber' value
    #emv_conversionflag - mapped to y or n based upon $Shop -> 'EVConversionFlag' value
    #emv_pagename       - hard-coded to "SF-CustomerOrder"
    #emv_value          - mapped to Order -> 'GrandTotal' value
    #emv_currency       - hard-coded to "GBP"
    #emv_transid        - mapped to Order -> 'Alias' value
    #emv_text1          - mapped to Order -> User -> 'Name' value
    #emv_text2          - mapped to Order -> User -> 'AddressExtension' value
    #emv_text3          - mapped to Order -> User -> 'Zipcode' value
    #emv_num1           - mapped to Order -> User -> 'Phone' value (filtered to extract just the numbers)
    #emv_num2           - mapped to sum of Order -> LineItemProducts -> 'Quantity' total values
    #emv_num3           - not mapped
    #emv_date1          - not mapped
    #emv_date2          - not mapped
    #emv_date3          - not mapped
    #emv_random         - mapped to random string created by GenerateRandomString function

    #URL
    #http://tre.emv3.com/P?key-value pairs	
    
    if($Order) {

        my $Site = $Order->get('Site');
        if($Site) {
    	    GetLog->debug("Site ID: ",$Site->get('ObjectID'));
    	    GetLog->debug("EVCustomerNumber: ",$Site->get('EVCustomerNumber'));
    	    GetLog->debug("EVConversionFlag: ",$Site->get('EVConversionFlag'));
    	    GetLog->debug("EVActive: ",$Site->get('EVActive'));
    	    GetLog->debug("LineItemContainerID: ",$LineItemContainer->get('ObjectID'));

            if($Site->get('EVActive')) {
                
                my $random_string = $self->_generateRandomString(16);
                my $uri = "";

                #Testing url only to prevent spamming of remote server...
                #$uri .= "http://appserver6.bargaincrazy.biggroup.co.uk/EmailVisionTest";

                $uri .= "https://tre.emv3.com/P";
                $uri .= "?" . "emv_client_id"      . "=" . $Site->get('EVCustomerNumber');
                $uri .= "&" . "emv_conversionflag" . "=" . ($Site->get('EVConversionFlag') ? "y" : "n");
                $uri .= "&" . "emv_pagename"       . "=" . "SF-CustomerOrder";
                $uri .= "&" . "emv_value"          . "=" . $LineItemContainer->get('GrandTotal');
                $uri .= "&" . "emv_currency"       . "=" . "GBP";
                $uri .= "&" . "emv_transid"        . "=" . $Order->get('Alias');
                $uri .= "&" . "emv_text1"          . "=" . uri_escape($User->get('Name'));
                $uri .= "&" . "emv_text2"          . "=" . uri_escape($BillingAddress->get('AddressExtension'));
                $uri .= "&" . "emv_text3"          . "=" . uri_escape($BillingAddress->get('Zipcode'));

                #The customer phone number filtered to just the digits
                my $Phone;
                my $FilteredPhone;
                if($BillingAddress->get('Phone')) {
                    $Phone = $BillingAddress->get('Phone');
                    while($Phone =~ m/(\d+)/g) {
                    	$FilteredPhone .= sprintf("%s",$1);
}               }         
                $uri .= "&" . "emv_num1"           . "=" . uri_escape($FilteredPhone);

                #The total quantity of items in the order
                my $TotalQuantity = 0;
                my $LineItemProducts =  eval { $LineItemContainer->childrenByClass('LineItemProduct') };
                if((scalar @$LineItemProducts) > 0) {
                    foreach my $LineItemProduct (@$LineItemProducts) {
                        $TotalQuantity += $LineItemProduct->get('Quantity');
                    }
                }
                $uri .= "&" . "emv_num2"           . "=" . $TotalQuantity;

                #Empty parameters not yet mapped to anything
                $uri .= "&" . "emv_num3"           . "=" . "";
                $uri .= "&" . "emv_date1"          . "=" . "";
                $uri .= "&" . "emv_date2"          . "=" . "";
                $uri .= "&" . "emv_date3"          . "=" . "";

                #Random string to help prevent caching
                $uri .= "&" . "emv_random"         . "=" . $random_string;

		return $uri;
	  }
  return;
	}
  return;	
    }
  return;
}


sub _generateRandomString
{
	GetLog->debug("GenerateRandomString function triggered...");

    my ($self, $string_length) = @_;
    my $random_string;
    
	GetLog->debug("String length: ",$string_length);

    if($string_length > 1) {
        my @chars=('a'..'z','A'..'Z','0'..'9','_');
        foreach (1..$string_length)
        {
            $random_string .= $chars[rand @chars];
        }
    }

	GetLog->debug("Random string: ",$random_string);

    return $random_string;
}


1;
